<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>记笔记</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            user-select: none;
        }
    </style>
    <link href="https://unpkg.com/@wangeditor/editor@latest/dist/css/style.css" rel="stylesheet">
    <style>
        #editor—wrapper {
            border: 1px solid #ccc;
            z-index: 100;
            /* 按需定义 */
        }

        #toolbar-container {
            border-bottom: 1px solid #ccc;
        }

        #editor-container {
            height: 500px;
        }

        .button {
            border-radius: 5px;
            display: inline-block;
        }

        .button:hover {
            background-color: rgba(0, 0, 0, 0.2);
        }

        .button:active {
            background-color: rgba(0, 0, 0, 0.1);
        }
    </style>
    <script src="https://unpkg.com/@wangeditor/editor@latest/dist/index.js"></script>
    <script>
        function formatTimeNew(inputTime = new Date()) {
            function getPeriod(hours) {
                if (hours >= 0 && hours < 6) {
                    return '凌晨';
                } else if (hours >= 6 && hours < 11) {
                    return '上午';
                } else if (hours >= 11 && hours < 14) {
                    return '中午';
                } else if (hours >= 14 && hours < 18) {
                    return '下午';
                } else {
                    return '晚上';
                }
            }

            function getWeekName(n) {
                switch (n) {
                    case 0:
                        return '星期天'
                    case 1:
                        return '星期一'
                    case 2:
                        return '星期二'
                    case 3:
                        return '星期三'
                    case 4:
                        return '星期四'
                    case 5:
                        return '星期五'
                    case 6:
                        return '星期六'
                }
            }
            let currentTime = new Date()
            let oneDaySecond = 86400000
            let currentDayStart = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime
                .getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000)
            let lastDayStart = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime
                .getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000 - oneDaySecond)
            let nextDayStart = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime
                .getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000 + oneDaySecond)
            let nextDayEnd = new Date(currentTime.getTime() - currentTime.getHours() * 60 * 60 * 1000 - currentTime
                .getMinutes() * 60 * 1000 - currentTime.getSeconds() * 1000 + oneDaySecond * 2)
            let prefix = ''
            if (inputTime >= currentDayStart && inputTime < nextDayStart) {
                prefix = '今天'
            }
            if (inputTime >= lastDayStart && inputTime < currentDayStart) {
                prefix = '昨天'
            }
            if (inputTime >= nextDayStart && inputTime < nextDayEnd) {
                prefix = '明天'
            }
            if (prefix == '') {
                prefix = (inputTime.getFullYear() == currentTime.getFullYear() ? '' : inputTime.getFullYear().toString() +
                    '年') + (inputTime.getMonth() + 1).toString() + '月' + inputTime.getDate() + '日 '
            }
            prefix += getPeriod(inputTime.getHours()) + ' '
            prefix += inputTime.getHours().toString() + ':'
            if (inputTime.getMinutes() < 10) {
                prefix += '0'
            }
            prefix += inputTime.getMinutes().toString() + ' '
            prefix += getWeekName(inputTime.getDay())
            return prefix
        }

        let noteInfo = {}

        function requestData(url, usePrefix = true, method = 'get', data = {}) {
            const urlPrefix = 'http://127.0.0.1:1000/api'
            return new Promise((resolve, reject) => {
                let data1 = {
                    method,
                    headers: {
                        'Content-Type': 'application/json', // 指定发送数据的类型
                    },
                }
                if (method == 'post') data1.body = JSON.stringify(data)
                fetch((usePrefix ? urlPrefix : '') + url, data1).then(async res => {
                    let re = await res.json()
                    return resolve(re)
                }).catch(e => {
                    console.log(e)
                    return resolve({
                        status: 0,
                        content: '请求失败'
                    })
                })
            })
        }

        async function init() {
            let re = location.href
            re = re.split('?')[1]
            re = re.split('&')
            let data = {}
            for (let i = 0; i < re.length; i++) {
                data[re[i].split('=')[0]] = re[i].split('=')[1]
            }
            console.log(data)

            let content = await requestData('/note/' + data.id)
            console.log(content)


            if (content.status == 1) {

                noteInfo = content.data

                document.getElementById('title').innerHTML = content.data.title
                document.getElementById('time').innerHTML = '上次编辑于' + formatTimeNew(new Date(content.data.time))

                console.log(content.data.title)

                const { createEditor, createToolbar } = window.wangEditor

                const editorConfig = {
                    placeholder: 'Type here...',
                    onChange(editor) {
                        const html = editor.getHtml()
                        noteInfo.content = html
                        console.log('editor content', html)
                        // 也可以同步到 <textarea>
                    }
                }

                const editor = createEditor({
                    selector: '#editor-container',
                    html: content.data.content,
                    config: editorConfig,
                    mode: 'default', // or 'simple'
                })

                const toolbarConfig = {}

                const toolbar = createToolbar({
                    editor,
                    selector: '#toolbar-container',
                    config: toolbarConfig,
                    mode: 'default', // or 'simple'
                })
            } else {
                alert(content.content)
                window.close()
            }
        }

        function handleEditTitle() {
            document.getElementById('titleInput').style.display = 'unset'
            document.getElementById('titleSave').style.display = 'unset'
            document.getElementById('title').style.display = 'none'
            document.getElementById('titleInput').value = document.getElementById('title').innerHTML
        }

        function handleSaveTitle() {
            document.getElementById('titleInput').style.display = 'none'
            document.getElementById('titleSave').style.display = 'none'
            document.getElementById('title').style.display = 'unset'
        }

        function handleInputTitle() {
            document.getElementById('title').innerHTML = document.getElementById('titleInput').value
            noteInfo.title = document.getElementById('titleInput').value
        }

        async function handleSave() {
            let re = await requestData('/save_note/' + noteInfo.id.toString(), true, 'post', noteInfo)
            if (re.status == 1) {
                alert('成功')
            } else {
                alert(re.content)
            }
        }

        async function handleDelete() {
            const userConfirmed = window.confirm("是否删除此笔记？");

            if (userConfirmed) {
                let re = await requestData('/delete_note/' + noteInfo.id.toString(), true, 'post', {})
                if (re.status == 1) {
                    alert('删除成功')
                    window.close()
                } else {
                    alert(re.content)
                }
            } else {
                // 用户点击了"取消"
                console.log("用户选择了否");
            }
        }
    </script>
</head>

<body onload="init()" style="width: 100vw;height: 100vh;overflow: hidden;">
    <div style="width: 100%;height: 60px;display: flex;align-items: center;justify-content: left;padding-left: 16px;">
        <span onclick="handleEditTitle()" style="font-size: 20px;" id="title"></span>
        <input oninput="handleInputTitle()"
            style="display: none;font-size: 18px;outline: 0;border: 0px;background-color: rgb(230,230,230);border-radius: 5px;line-height: 1.5;padding: 5px;"
            id="titleInput" type="text">
        <div onclick="handleSaveTitle()" style="padding: 2px 5px;margin-left: 5px;display: none;" id="titleSave"
            class="button">
            确定
        </div>
        <span id="time" style="font-size: 14px;color: gray;margin-left: 10px;"></span>
        <div onclick="handleSave()"
            style="width: 35px;height: 35px;display: inline-block;position: absolute;right: 13px;top: 13px;padding-left: 6px;padding-top: 6px;"
            class="button">
            <svg width="22" height="22" viewBox="0 0 48 48" fill="currentColor">
                <path fill-rule="evenodd" clip-rule="evenodd"
                    d="M32.38 4a4 4 0 012.832 1.175l7.62 7.64A4 4 0 0144 15.64V42a2 2 0 01-2 2H6a2 2 0 01-2-2V6a2 2 0 012-2h26.38zM12 8H8v32h32V16.83a2 2 0 00-.584-1.412l-6.81-6.83A2 2 0 0031.19 8H31v14a2 2 0 01-2 2H14a2 2 0 01-2-2V8zm15 0H16v12h3.999L20 14a1 1 0 011-1h2a1 1 0 011 1v6h3V8z"
                    fill="currentColor" />
            </svg>
        </div>
        <div onclick="handleDelete()"
            style="width: 35px;height: 35px;display: inline-block;position: absolute;right: 55px;top: 13px;padding-left: 6px;padding-top: 6px;"
            class="button">
            <svg width="22" height="22" viewBox="0 0 48 48" fill="currentColor">
                <path fill-rule="evenodd" clip-rule="evenodd"
                    d="M30 4a2 2 0 012 2l-.001 1.999L42.719 8c.445 0 .606.046.77.134.162.087.29.215.377.378.088.163.134.324.134.77v1.436c0 .446-.046.607-.134.77a.908.908 0 01-.378.378c-.163.088-.324.134-.77.134L40 11.999 40 42a2 2 0 01-2 2H10a2 2 0 01-2-2l-.001-30.001L5.282 12c-.446 0-.607-.046-.77-.134a.908.908 0 01-.378-.378c-.088-.162-.134-.324-.134-.77V9.282c0-.446.046-.607.134-.77a.909.909 0 01.378-.378c.163-.088.324-.134.77-.134l10.717-.001L16 6a2 2 0 012-2h12zm5.999 7.999h-24L12 40h24l-.001-28.001zM21 18a1 1 0 011 1v14a1 1 0 01-1 1h-2a1 1 0 01-1-1V19a1 1 0 011-1h2zm8 0a1 1 0 011 1v14a1 1 0 01-1 1h-2a1 1 0 01-1-1V19a1 1 0 011-1h2z"
                    fill="currentColor" />
            </svg>
        </div>
    </div>
    <div id="editor—wrapper" style="position: fixed;width: 100%;left: 0;top: 60px;height: calc(100% - 60px);">
        <div id="toolbar-container"><!-- 工具栏 --></div>
        <div id="editor-container"><!-- 编辑器 --></div>
    </div>
</body>

</html>